package org.ww.jd.auction;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.ww.jd.JDURLConsts;
import org.ww.jd.log.Logger;
import org.ww.jd.utils.HttpClientUtils;

public class UnSessionUtils {
	public static void main(String[] args) {
		List<GoodsInfo> searchAuction = searchAuction("");
		for (GoodsInfo goodsInfo : searchAuction) {
			System.out.println(goodsInfo);
		}
	}

	public static List<GoodsInfo> searchAuction(String keyword) {
		return searchAuction(false, keyword);
	}

	public static List<GoodsInfo> searchAuction(boolean onlyId, String keyword) {
		if (keyword != null && !keyword.isEmpty()) {
			keyword = keyword.trim().replaceAll(" ", "%20");
		}
		List<GoodsInfo> goodsList = new ArrayList<GoodsInfo>();
		String searchLocaltion = createSearchUrl(1, keyword);
		int pageNo = 1;
		try {
			Document doc = HttpClientUtils
					.doGetHtml(searchUrl(searchLocaltion));

			Elements pageInfos = doc.getElementsByAttributeValue("class",
					"p-num");
			if (!pageInfos.isEmpty()) {
				Elements pages = pageInfos.get(0).getElementsByTag("a");
				int size = pages.size();
				Element el = pages.get(size - 2);
				pageNo = Integer.valueOf(el.ownText());
			}
		} catch (Exception e) {
			Logger.error(e);
		}
		Logger.debug("total page:" + pageNo);
		for (int i = 0; i < pageNo; i++) {
			try {
				Logger.debug("current page:" + (i + 1));
				goodsList.addAll(searchAuctionImpl(i + 1, onlyId, keyword));
			} catch (Exception e) {
				Logger.debug("error on page[" + (i + 1) + "]," + e.getMessage());
				Logger.error(e);
			}
		}
		return goodsList;
	}

	private static List<GoodsInfo> searchAuctionImpl(int pageNo,
			boolean onlyId, String keyword) {

		List<GoodsInfo> goodsList = new ArrayList<GoodsInfo>();
		String searchLocaltion = createSearchUrl(pageNo, keyword);
		Document doc = HttpClientUtils.doGetHtml(searchUrl(searchLocaltion));
		Elements elementsByClass = doc.getElementsByAttributeValue("class",
				"auctionList clearfix");
		if (elementsByClass == null || elementsByClass.isEmpty()) {
			return goodsList;
		}
		Elements uls = elementsByClass.get(0).getElementsByTag("ul");
		if (uls == null || uls.isEmpty()) {
			return goodsList;
		}
		Element paimailist = uls.get(0);
		if (paimailist == null) {
			return goodsList;
		}
		Elements goodsInfos = paimailist.getElementsByTag("li");
		for (Element goodsInfo : goodsInfos) {
			String id = goodsInfo.attr("id").replaceAll("li-", "");
			if (id == null || id.trim().length() == 0) {
				continue;
			}
			Element paimaiType = goodsInfo.getElementById("paimaitype_" + id);
			String typeClass = paimaiType.attr("class");
			if (typeClass.indexOf("direct") > -1) {
				continue;
			}
			GoodsInfo goodsInfoVO;
			if (onlyId) {
				goodsInfoVO = new GoodsInfo(id);
			} else {
				goodsInfoVO = getGoods(id);
			}
			if (goodsInfoVO != null) {
				goodsList.add(goodsInfoVO);
			}
		}
		return goodsList;
	}

	private static String searchUrl(String searchLocaltion) {
		return "http://auction.jd.com" + searchLocaltion;
	}

	private static String createSearchUrl(int pageNo, String keyword) {
		if (keyword == null || keyword.isEmpty()) {
			keyword = "";
		}
		String searchLocaltion = "/auctionList.html?searchParam=" + keyword
				+ "&enc=utf-8&limit=40&page=" + pageNo;
		return searchLocaltion;
	}

	// public static GoodsShortcut getGoodsShortcut(String goodsid) {
	// JSONArray infos = HttpClientUtils.doGetJsonArray(
	// JDURLConsts.AUCTION_URL
	// + "json/current/queryList.action?paimaiIds=" + goodsid);
	// try {
	// JSONObject json = infos.getJSONObject(0);
	// double currentPrice = json.getDouble("currentPrice");
	// long remainTime = json.getLong("remainTime");
	// int auctionStatus = json.getInt("auctionStatus");
	// return new GoodsShortcut(remainTime, auctionStatus, currentPrice);
	// } catch (JSONException e) {
	// Logger.error(e);
	// throw new RuntimeException(e);
	// }
	//
	// }

	public static GoodsInfo getGoods(String goodsid) {
		Document doc = HttpClientUtils.doGetHtml(JDURLConsts.AUCTION_URL + "/"
				+ goodsid);
		Elements elements = doc.getElementsByAttributeValue("class",
				"intro_detail");
		if (elements.size() == 0) {
			return null;
		}
		String className = "";
		// 导航
		Elements breadcrumbs = doc.getElementsByAttributeValue("class",
				"atc_breadcrumb");
		if (breadcrumbs.size() > 0) {
			Elements hrefs = breadcrumbs.get(0).getElementsByTag("a");
			if (!hrefs.isEmpty()) {
				Element a = hrefs.get(hrefs.size() - 1);
				className = a.ownText();
			}

		}
		Element goodsNode = elements.get(0);
		GoodsInfo goodsInfo = HtmlUtils.convertGoodsInfo(className, goodsid,
				goodsNode);
		String sku = goodsNode.getElementById("productId").attr("value");
		JSONObject jdPriceJson = HttpClientUtils.doGetJson(
				JDURLConsts.AUCTION_URL + "json/current/queryJdPrice?sku="
						+ sku + "&paimaiId=" + goodsid, searchUrl(goodsid));
		try {

			String jdPriceString = StringUtils.toString(jdPriceJson
					.get("jdPrice"));
			Double jdPrice = Double.parseDouble(jdPriceString);
			goodsInfo.setJDPrice(jdPrice);
		} catch (NumberFormatException e) {
			goodsInfo.setJDPrice(-1.0);
		} catch (JSONException json) {
			goodsInfo.setJDPrice(-1.0);
			// Logger.error(json);
		}
		// http://paimai.jd.com/json/current/queryList.action?paimaiIds=10160745
		String url = JDURLConsts.AUCTION_URL
				+ "json/current/queryList.action?paimaiIds=" + goodsid;
		JSONArray infos = null;
		try {
			infos = HttpClientUtils.doGetJsonArray(url);
		} catch (Exception e) {
			Logger.error(e.getMessage());
			return null;
		}
		try {

			Object jsonFirst = infos.get(0);
			if (!(jsonFirst instanceof JSONObject)) {
				return null;
			}
			JSONObject json = (JSONObject) jsonFirst;
			goodsInfo.setCurrentPrice(json.getDouble("currentPrice"));
			goodsInfo.setStartTimeMili(json.getLong("startTime"));
			goodsInfo.setEndTimeMili(json.getLong("endTime"));
		} catch (JSONException e1) {
			System.out.println("error url:" + url);
			throw new RuntimeException(e1);
		}
		return goodsInfo;
	}

}
